<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkRoom\Listener;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use MoChat\App\Corp\Contract\CorpContract;
use MoChat\App\WorkRoom\Event\UpdateRoomRawEvent;
use MoChat\App\WorkRoom\Queue\SyncDetailQueue;
use Psr\Container\ContainerInterface;

/**
 * 客户群变更事件
 * 客户群被修改后（群名变更，群成员增加或移除，群主变更，群公告变更），回调该事件。
 * 收到该事件后，企业需要再调用获取客户群详情接口，以获取最新的群详情。
 *
 * @Listener(priority=9999)
 */
class UpdateRoomRawListener implements ListenerInterface
{
    /**
     * @Inject
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * @var CorpContract
     */
    private $corpService;

    public function listen(): array
    {
        return [
            UpdateRoomRawEvent::class,
        ];
    }

    /**
     * @param UpdateRoomRawEvent $event
     */
    public function process(object $event)
    {
        try {
            $message = $event->message;
            $this->logger = $this->container->get(StdoutLoggerInterface::class);
            $this->corpService = $this->container->get(CorpContract::class);

            $corp = $this->corpService->getCorpByWxCorpId($message['ToUserName'], ['id']);
            if (empty($corp)) {
                $this->logger->error(sprintf('[客户群变更事件]未找到指定的企业，企业ID:%s', $message['ToUserName']));
            }

            $wxRoom = [
                'chat_id' => $message['ChatId'],
                'status' => 0,
            ];
            (new SyncDetailQueue())->handle((int) $corp['id'], $wxRoom);
        } catch (\Throwable $e) {
            $this->logger->error(sprintf('[客户群变更事件]监听失败，错误信息: %s', $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
        }
    }
}
